package com.jacobson.huobi.mvp

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.util.Base64
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSONObject
import com.jacobson.core.base.Immersive
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.ActivityModule
import com.jacobson.core.mvp.BaseMvpActivity
import com.jacobson.huobi.Constants
import com.jacobson.huobi.R
import com.jacobson.huobi.di.components.DaggerLoginActivityComponent
import com.jacobson.huobi.di.modules.LoginActivityModule
import com.jacobson.huobi.entities.LoginUserInfo
import com.jacobson.huobi.entities.RegisterInfo
import com.jacobson.huobi.entities.events.LoginEvent
import com.jacobson.huobi.entities.response.CommonResponse
import com.jacobson.huobi.entities.response.LoginPageResponse
import com.jacobson.huobi.entities.vo.LoginRespVo
import com.jacobson.huobi.mvp.contract.LoginContract
import com.jacobson.huobi.mvp.fragment.SymbolFragment
import com.jacobson.huobi.threads.TokenThread
import com.jacobson.huobi.utils.*
import com.jacobson.huobi.utils.SettingProperties.KEY_LOGIN_PASSWORD
import com.jacobson.huobi.utils.SettingProperties.KEY_LOGIN_PHONE
import com.jacobson.huobi.websocket.ProtocolFactory
import com.jacobson.huobi.websocket.WebsocketManager
import kotlinx.android.synthetic.main.activity_kyc_auth.btnBack
import kotlinx.android.synthetic.main.activity_login.*
import org.simple.eventbus.EventBus
import java.util.regex.Pattern

@Immersive(fitSystemWindows = false)
class LoginActivity :
    BaseMvpActivity<LoginContract.Presenter>(), LoginContract.View {

/*    //登陆手机号
    private val KEY_LOGIN_PHONE = "_key_login_phone_"
    //登陆密码
    private val KEY_LOGIN_PASSWORD = "_key_login_password_"*/


    //当前页面状态   1：注册 2：账号密码登陆  3：手机验证码登陆  默认：2
    private var currentPageType = 2
    //注册
    private var PAGE_TYPE_REGISTER = 1
    //账号密码登陆
    private var PAGE_TYPE_NORMAL_LOGIN = 2
    //手机验证码登陆
    private var PAGE_TYPE_PHONE_LOGIN = 3
    //登陆注册公用按钮 默认登陆页面 显示注册按钮
    private var isLoginFragment = true

    private var loginRespVo: LoginRespVo? = null
    //保存验证码的key
    private var kaptchaKey: String = ""

    private lateinit var timer: VertiCodeTimer

    override fun onCreate(savedInstanceState: Bundle?) {
        if (TokenStorageUtil.read()!=null){
            MainActivity.startHomeActivity(this,0)
            finish()
        }
        super.onCreate(savedInstanceState)
        //修改底部功能键背景色 只支持api为21及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor =
                ResourcesUtil.getColor(R.color.colorPrimary) //设定底部导航栏  同全局颜色
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerLoginActivityComponent.builder()
            .loginActivityModule(LoginActivityModule(this))
            .appComponent(appComponent)
            .activityModule(ActivityModule(this))
            .build()
            .inject(this)
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.activity_login

    override fun initData(savedInstanceState: Bundle?) {

        timer = VertiCodeTimer(60000, 1000, btnRefreshVertiCode)
        initBtnClick()
        initFocus()
        initItem(false)
        //初始化加载登陆验证码
        presenter.getKaptcha()
    }

    /**
     * 获取手机验证码
     */
    private fun getVertiCode(phoneNumber: String) {
        presenter.getVertiCode(phoneNumber)
    }

    /**
     * 注册用户
     */
    private fun registerUser() {
        var password = etPassword.text.trim().toString()
        var repeatPassword = etRepeatPassword.text.trim().toString()
        var phoneNumber = etPhoneNumber.text.trim().toString()
        var vertiCode = etVertiCode.text.trim().toString()
        var sharedUserId = etSharedUserId.text.trim().toString()


        if (phoneNumber.isNullOrBlank()) {
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (password.isNullOrBlank()) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (repeatPassword.isNullOrBlank()) {
            Toast.makeText(this, "重复密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (password != repeatPassword) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show()
            return
        }else {
            if (!DataUtil.isLetterDigit(password) || password.length < 8) {
                Toast.makeText(this, "密码至少8位且必须包含英文和数字", Toast.LENGTH_SHORT).show()
                return
            }
        }

        if (vertiCode.isNullOrBlank()) {
            Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show()
            return
        }

        if (sharedUserId.isNullOrBlank()) {
            Toast.makeText(this, "邀请码不能为空", Toast.LENGTH_SHORT).show()
            return
        }else{
            var s = isPhoneNumber(sharedUserId)
            var ss = isInvitedCode(sharedUserId)
            if(!(isPhoneNumber(sharedUserId) or isInvitedCode(sharedUserId))){

                Toast.makeText(this, "请输入正确手机号或UID", Toast.LENGTH_SHORT).show()
            }
        }

        password = EncryptUtil.encrypData(password , vertiCode)
        if (password.isNullOrBlank()) {
            Toast.makeText(this, "密码加密出错,请联系管理员", Toast.LENGTH_SHORT).show()
            return
        }
        var registerInfo = RegisterInfo( password,
            phoneNumber, vertiCode,sharedUserId)
        presenter.registerUser(registerInfo)
    }

    /**
     * 登陆用户
     */
    private fun login() {
        var phoneNumber = etPhoneNumber.text.trim().toString()
        var password = etPassword.text.trim().toString()
        var checkCode = etCheckCode.text.trim().toString()

        if (phoneNumber.isNullOrBlank()) {
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (password.isNullOrBlank()) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (checkCode.isNullOrBlank()) {
            Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        password = EncryptUtil.encrypData(password, checkCode)
        if (password.isNullOrBlank()) {
            Toast.makeText(this, "密码加密失败", Toast.LENGTH_SHORT).show()
            return
        }
        presenter.login(LoginUserInfo(phoneNumber, password, kaptchaKey, checkCode))
    }
    /**
     * 获取验证码响应操作
     */
    override fun onVertiCodeResultResp(response: LoginPageResponse) {
        if (response.code == Constants.RESP_OK) {
            Toast.makeText(this,"发送短信成功",Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, response.msg, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 获取登陆验证码
     */
    override fun onGetKaptchaResultResp(response: CommonResponse<JSONObject>) {
        if (response.code == Constants.RESP_OK) {

            var data = response.data

            //Base64编码地址(地址太长，省略)
            var base64String = data.getString("data").split(",")[1]
            kaptchaKey  = data.getString("key")
            if (base64String.isEmpty() || kaptchaKey!!.isEmpty()) {
                Toast.makeText(this, "无法获取到验证码", Toast.LENGTH_SHORT).show()
            }
            //将Base64编码字符串解码成Bitmap
            var base64ByteArray = Base64.decode(base64String, Base64.DEFAULT)
            var bitmap = BitmapFactory.decodeByteArray(base64ByteArray, 0 , base64ByteArray.size)
            //设置ImageView图片
            btnRefreshCheckCode.setImageBitmap(bitmap)
        } else {
            Toast.makeText(this, response.msg, Toast.LENGTH_SHORT).show()
        }
    }

    override fun onLoginResultResp(response: CommonResponse<JSONObject>) {
        logger.d("登陆返回编码:" + response.code)
        SettingProperties.setCommonValue(KEY_LOGIN_PHONE, etPhoneNumber.text.trim().toString())
        SettingProperties.setCommonValue(KEY_LOGIN_PASSWORD, etPassword.text.trim().toString())

        if (response.code == Constants.RESP_OK) {
            var data = response.data
            try {
                data.put("refresh_times", System.currentTimeMillis())
                TokenStorageUtil.save(data.toJSONString())
                EventBus.getDefault().post(LoginEvent(1, null))
                TokenThread.start()
                MainActivity.startHomeActivity(this, SymbolFragment.ME)
                WebsocketManager.sendMessage(ProtocolFactory.ofCommitAccessToken(data.getString("access_token")))
//                EventBus.getDefault().post(LoginEvent(2, null))
                finish()
            }catch (e:Exception) {
                logger.e("解析登陆返回信息失败",e)
                Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show()
            }
        }else if (response.code == -10000) {
            Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show()
        }else {
            Toast.makeText(this, response.msg, Toast.LENGTH_SHORT).show()
        }
    }


    /**
     * 注册用户响应操作
     */
    override fun onRegisterResultResp(response: LoginPageResponse) {
        if (response.code == Constants.RESP_OK) {
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show()
            tvLoginTitle.text = "账号登陆"
            btnLoginAndRegister.text = "登陆"
//            etUserName.hint = "登陆手机号"
            etPassword.hint = "登陆密码"
            llPassword.visibility = View.VISIBLE
            llCheckCode.visibility = View.VISIBLE
            llVertiCode.visibility = View.GONE
            llRepeatPassword.visibility = View.GONE
            llPhone.visibility = View.VISIBLE
            btnUserNameLogin.visibility = View.GONE
            btnRegister.visibility = View.VISIBLE
            btnPhoneLogin.visibility = View.INVISIBLE
            llSharedUserId.visibility = View.GONE
            isLoginFragment = true
            currentPageType = 2
        }else {
            Toast.makeText(this, "注册失败,请联系管理员", Toast.LENGTH_SHORT).show()
        }
    }
    private val mHits = LongArray(2)
    override fun onError(type: Int, extra: Any?, code: Int, message: String): Boolean {
        logger.e("error >>> $message")
        Toast.makeText(this, "$message", Toast.LENGTH_SHORT).show()
        return super.onError(type, extra, code, message)
    }
    override fun onBackPressed() {
        if (back()) return
        super.onBackPressed()
    }

    private fun back(): Boolean {
        System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
        mHits[mHits.size - 1] = SystemClock.uptimeMillis()
        if (mHits[0] >= SystemClock.uptimeMillis() - 2000) {
            android.os.Process.killProcess(android.os.Process.myPid());
        } else {
            Toast.makeText(this, "再按一次返回键才让退出CeLueRen", Toast.LENGTH_SHORT).show()
            return true
        }
        return false
    }

    /**
     * 初始化点击事件
     */
    private fun initBtnClick() {
        btnBack.setOnClickListener {
            if(btnUserNameLogin.visibility==View.VISIBLE){
                tvLoginTitle.text = "账号登陆"
                btnLoginAndRegister.text = "登陆"
                //            etUserName.hint = "登陆手机号"
                etPassword.hint = "登陆密码"
                llPassword.visibility = View.VISIBLE
                llCheckCode.visibility = View.VISIBLE
                llVertiCode.visibility = View.GONE
                llRepeatPassword.visibility = View.GONE
                llPhone.visibility = View.VISIBLE
                btnUserNameLogin.visibility = View.GONE
                btnRegister.visibility = View.VISIBLE
                btnPhoneLogin.visibility = View.INVISIBLE
                llSharedUserId.visibility = View.GONE
                isLoginFragment = true
                currentPageType = 2
                initItem(false)
            }else {
                if (back()) {
                    return@setOnClickListener
                }
                this.finish()
            }
        }
        btnPhoneLogin.setOnClickListener {
            ForgetActivity.startActivity(this)
        }
        //注册页面
        btnRegister.setOnClickListener {
            tvLoginTitle.text = "账号注册"
            btnLoginAndRegister.text = "注册"
            //            etUserName.hint = "注册账号"
            etPassword.hint = "注册密码"
            llPassword.visibility = View.VISIBLE
            llRepeatPassword.visibility = View.VISIBLE
            llSharedUserId.visibility = View.VISIBLE
            llCheckCode.visibility = View.GONE
            llPhone.visibility = View.VISIBLE
            llVertiCode.visibility = View.VISIBLE
            btnRegister.visibility = View.GONE
            btnUserNameLogin.visibility = View.VISIBLE
            btnPhoneLogin.visibility = View.INVISIBLE
            isLoginFragment = false
            currentPageType = 1
            initItem(true)
        }
        //账号密码登陆页面
        btnUserNameLogin.setOnClickListener {
            tvLoginTitle.text = "账号登陆"
            btnLoginAndRegister.text = "登陆"
            //            etUserName.hint = "登陆手机号"
            etPassword.hint = "登陆密码"
            llPassword.visibility = View.VISIBLE
            llCheckCode.visibility = View.VISIBLE
            llVertiCode.visibility = View.GONE
            llRepeatPassword.visibility = View.GONE
            llPhone.visibility = View.VISIBLE
            btnUserNameLogin.visibility = View.GONE
            btnRegister.visibility = View.VISIBLE
            btnPhoneLogin.visibility = View.INVISIBLE
            llSharedUserId.visibility = View.GONE
            isLoginFragment = true
            currentPageType = 2
            initItem(false)
        }
//        //手机号登陆页面
//        btnPhoneLogin.setOnClickListener {
//            tvLoginTitle.text = "手机验证码登陆"
//            btnLoginAndRegister.text = "登陆"
//    //            etUserName.hint = "手机号"
//            llPassword.visibility = View.GONE
//            llCheckCode.visibility = View.GONE
//            llRepeatPassword.visibility = View.GONE
//            llVertiCode.visibility = View.VISIBLE
//            llPhone.visibility = View.GONE
//            btnUserNameLogin.visibility = View.VISIBLE
//            btnRegister.visibility = View.VISIBLE
//            btnPhoneLogin.visibility = View.INVISIBLE
//            isLoginFragment = true
//            currentPageType = 3
//        }

        //刷新登陆验证码
        btnRefreshCheckCode.setOnClickListener {
            presenter.getKaptcha()
        }

        //刷新手机号验证码
        btnRefreshVertiCode.setOnClickListener {
            val phoneNumber = etPhoneNumber.text.trim().toString()
            if (phoneNumber.isBlank()) {
                Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show()
            } else {
                if (checkPhoneNum(phoneNumber)) {
                    getVertiCode(phoneNumber)
                    timer.start()
                } else {
                    Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show()
                }

            }
        }

        /**
         * 注册/登录
         */
        btnLoginAndRegister.setOnClickListener {
            if (currentPageType == PAGE_TYPE_REGISTER) {
                registerUser()
            }else if (currentPageType == PAGE_TYPE_NORMAL_LOGIN) {

                login()

            }
        }
        /**
         * 推荐码
         */
        tvSharedUserId.setOnClickListener {
            AlertDialog.Builder(this@LoginActivity)
                .setTitle("推荐码说明")
                .setMessage("1、推荐码是已注册的会员uid或手机号码,为必填项. \n" +
                        "2、如果没有推荐人可以填系统UID:8888888")
                .setPositiveButton("确定", null)
                .show()

        }
    }

    /**
     * 初始化焦点事件
     */
    private fun initFocus() {
        etRepeatPassword.setOnFocusChangeListener { _, b ->
            if (currentPageType == PAGE_TYPE_REGISTER && !b) {
                var password = etPassword.text.trim().toString()
                var repeatPassword = etRepeatPassword.text.trim().toString()
                if(password != repeatPassword) {
                    Toast.makeText(this, "两次输入的密码不一样", Toast.LENGTH_SHORT).show()
                }
            }
        }

        etPassword.setOnFocusChangeListener { _, b ->
            if (currentPageType == PAGE_TYPE_REGISTER && !b) {
                var password = etPassword.text.trim().toString()
                if (!DataUtil.isLetterDigit(password) || password.length < 8) {
                    Toast.makeText(this, "密码至少8位且必须包含英文和数字", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 初始化组件
     */
    private fun initItem(isClear: Boolean) {
        if (!isClear) {
            etPhoneNumber.setText(SettingProperties.getCommonValue(KEY_LOGIN_PHONE))
            etPassword.setText(SettingProperties.getCommonValue(KEY_LOGIN_PASSWORD))
        }else {
            etPhoneNumber.setText("")
            etPassword.setText("")
        }
    }
    /***
     * 手机号码检测
     */
    private fun checkPhoneNum(num: String): Boolean {
        val regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[5-9])|(166)|(19[8,9])|)\\d{8}$"
        val p = Pattern.compile(regExp)
        val m = p.matcher(num)
        return m.matches()
    }

    private fun isInvitedCode(code :String):Boolean{
        val USER_ID = "^\\d{8}$"
        return Pattern.compile(USER_ID).matcher(code).find()
    }
    private fun isPhoneNumber(code :String):Boolean{
        val TELEPHONE = "^1([38]\\d|5[0-35-9]|7[3678])\\d{8}$"
        return Pattern.compile(TELEPHONE).matcher(code).find()
    }
    companion object {
        fun startActivity(context: Context) {
            Intent(context, LoginActivity::class.java).run {
                context.startActivity(this)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}
